<template>
  <div style="position:absolute;left:0;top:0;right:0;bottom:0;">
    <Header />
    <div style="display:flex;position:absolute;top:93px;left:0;right:0;bottom:0">
      <div style="width:88px;height: 100%;position: relative">
        <slider-bar />
      </div>
      <div style="flex: 1;height: 100%; position: relative">
        <scene-viewer
          @onPopuPosition="onPopuPosition"
          @onSelectedLayer="onSelectedLayer"
          @onInitSceneViewer="onInitSceneViewer"
        />
        <SceneTwoMap @oneMapInstanceComplete="oneMapInstanceComplete" />
        <attribute />
        <!-- <LayerLegend /> -->
        <!-- <chart /> -->
        <river-survey />
        <base-map />
        <scene-pop ref="scenePop" :is-visible="isShowScenePop" />
        <MapToolbar @onDoubleScreenSwitch="onDoubleScreenSwitch" />
        <div :class="mapModuleIndex===2?'mapFunction_esw':'mapFunction'">
          <sceneModule v-show="mapModuleIndex==1||mapModuleIndex==2" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SceneTwoMap from "@/components/map/SceneTwoMap";
import SceneViewer from "@/components/scene/scene"; // 场景控件
import MapToolbar from "@/pages/yzt/components/mapToolbar"; // 地图工具
import SceneModule from "@/pages/yzt/components/sceneModule"; // 场景功能
import Attribute from "@/pages/yzt/components/attribute"; // 属性表
import scenePop from "@/pages/yzt/components/scenePop"; // 属性弹出
// import LayerLegend from '@/pages/yzt/components/legend' // 图例
import BoxUtil from "@/assets/js/utils/BoxUtil";
import { SceneTool } from "@/pages/yzt/components/SceneTool";
import "@/assets/mapbox/libs/draw/mapbox-gl-draw.css";
import MapBoxDraw from "@/assets/mapbox/libs/draw/mapbox-gl-draw.js";
import SmQuery from "@/assets/js/utils/SmQuery";
import LayerSelector from "@/pages/yzt/components/layerselector";
import HgcMapBoxUtil from "@/assets/js/mapboxgl";
import MapService from "@/pages/yzt/components/mapservice";
import SliderBar from "@/pages/yzt/components/sliderbar";
import BaseMap from "@/pages/yzt/components/basemap";
import SortFactory from "@/assets/js/mapboxgl/sortfactory";
import { mapState, mapGetters } from "vuex";
import MeasureSync from "@/components/map/measureSync";
import Header from "@/pages/yzt/components/header/Header";
import RiverSurvey from "@/pages/yzt/components/riverSurvey";
import Symbol from "@/assets/js/mapboxgl/symbol";
export default {
  name: "Index",
  components: {
    SceneTwoMap,
    Attribute,
    SceneViewer,
    MapToolbar,
    // LayerLegend,
    SceneModule,
    scenePop,
    SliderBar,
    BaseMap,
    Header,
    RiverSurvey
  },
  data: function() {
    return {
      properties: {},
      dictionary: undefined,
      isShowScenePop: undefined,
      index: 0
    };
  },
  methods: {
    // 地图初始化
    oneMapInstanceComplete(left, right, compare) {
      const sfLeft = new SortFactory(left);
      //sfLeft.addSortLayer("qxj", -1, "行政区界线");
      sfLeft.addSortLayer("measure-source", -1, "测量控件");
      sfLeft.addSortLayer("bufferQuery-source", 0, "缓冲区查询面");
      sfLeft.registerAllLayers(this.allBaseMapLayers); // 注册底图数据
      sfLeft.registerAllLayers(this.allLayers); // 注册专题数据
      const mapLeft = new HgcMapBoxUtil(left, sfLeft); // 地图控制
      this.mapServiceLeft = new MapService(mapLeft, sfLeft); // 实例化地图基础操作类
      this.$store.commit("eswyzt/setLeftService", this.mapServiceLeft);

      const sfRight = new SortFactory(right);
      //sfRight.addSortLayer("qxj", -1, "行政区界线");
      sfRight.addSortLayer("measure-source", -1, "测量控件");
      sfRight.addSortLayer("bufferQuery-source", 0, "缓冲区查询面");

      sfRight.addSortLayer("test", -1, "test");

      sfRight.registerAllLayers(this.allBaseMapLayers); // 注册底图数据
      sfRight.registerAllLayers(this.allLayers); // 注册专题数据
      const mapRight = new HgcMapBoxUtil(right, sfRight); // 地图控制
      this.mapServiceRight = new MapService(mapRight, sfRight); // 实例化地图基础操作类
      this.$store.commit("eswyzt/setRightService", this.mapServiceRight);

      const measure = new MeasureSync(
        this.mapServiceLeft,
        this.mapServiceRight
      );
      this.$store.commit("eswyzt/setMeasureSync", measure);
      this.$store.commit("eswyzt/setComparable", compare);
      this.$store.commit("eswyzt/setMapService", this.mapServiceRight);

      this.mapServiceRight.on("map.init", this.mapInitComplete, this);
      this.mapServiceRight.on("map.click", this.mapClickEvent, this); // 图层click

      this.bus.$emit("onMapInit", this.mapServiceRight);
    },

    onDoubleScreenSwitch(visible) {
      this.$store.commit("eswyzt/setLayerSelectorVisible", visible);
      if (!visible) {
        // 关闭双屏对比
        this.mapServiceRight.clearRemoteImageLayers();
      }
    },

    onInitSceneViewer(viewer) {},
    /**
     *
     * 选择事件
     * @param map
     * @param e
     * @param id
     */
    mapClickEvent(e) {
      var feature = e.features.length > 0 && e.features[0];
      let attribute;
      try {
        var layers = this.allLayers.filter(i => i._id === feature.source);
        attribute = JSON.parse(layers.length > 0 && layers[0].attribute);
      } catch (e) {
        attribute = {};
      }
      this.mapServiceRight.openPop(feature, attribute, e.lngLat);
    },
    /**
     * 地图sytle.load加载完成
     */
    mapInitComplete() {
      this.$store.dispatch("eswyzt/RequestSysSymbols").then(res => {
        this.mapServiceRight.setCreateDrawControl(res);
      });
      var right = this.mapServiceRight.getMap();

      var flashingSquare = {
        width: 164,
        height: 164,
        data: new Uint8Array(164 * 164 * 4),

        onAdd: function(map) {
          this.map = map;
        },

        render: function() {
          // keep repainting while the icon is on the map
          this.map.triggerRepaint();

          // alternate between black and white based on the time
          var value = Math.round(Date.now() / 1000) % 2 === 0 ? 255 : 0;

          // check if image needs to be changed
          if (value !== this.previousValue) {
            this.previousValue = value;

            var bytesPerPixel = 4;
            for (var x = 0; x < this.width; x++) {
              for (var y = 0; y < this.height; y++) {
                var offset = (y * this.width + x) * bytesPerPixel;
                this.data[offset + 0] = value;
                this.data[offset + 1] = value;
                this.data[offset + 2] = value;
                this.data[offset + 3] = 255;
              }
            }

            // return true to indicate that the image changed
            return true;
          }
        }
      };

      //right.addImage("flashing_square", flashingSquare);
      right.loadImage("/static/img/symbols/泵.png",(e,i)=>{
         right.addImage('flashing_square',i, { pixelRatio: 2 })
      })

      right.addSource("test", {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [
            {
              type: "feature",
              geometry: { type: "Point", coordinates: [126, 45] }
            }
          ]
        }
      });
      this.mapServiceRight.getSf().addLayer("test", {
        id: "a333",
        type: "symbol",
        source: "test",
        //  paint: {
        //                 "circle-radius": 6,
        //                 "circle-color": "#ff0000",
        //                 "circle-opacity": 1,
        //                 "circle-stroke-width": 2,
        //                 "circle-stroke-color": "#ff0000",
        //                 "circle-stroke-opacity": 0.5
        //             },
        layout: {
          "icon-image": "flashing_square",
          "icon-size" : 1
        }
      });
    },

    /**
     * 更新气泡位置
     */
    onPopuPosition(bottom, left) {
      if (this.$refs["scenePop"].$el.style) {
        this.$refs["scenePop"].$el.style.left = left;
        this.$refs["scenePop"].$el.style.bottom = bottom;
      }
    },
    /**
     *
     * @param layer
     */
    onSelectedLayer(layer) {
      // 查找对应图层，属性信息和查询配置信息
      if (this.indexMap && this.indexMap[layer.name]) {
        var selections = layer.getSelection();
        if (selections.length > 0) {
          var selectID = selections[0];
          var sqlfilter = "SmID =" + selectID;

          var data = SmQuery.mapServiceLayerSearchBySQL(
            this.indexMap[layer.name].searchConfig.layerName,
            sqlfilter,
            this.indexMap[layer.name].searchConfig.url,
            0,
            9999
          );
          let attr = {};
          try {
            attr = JSON.parse(this.indexMap[layer.name].attribute);
          } catch (e) {
            attr = {};
          }
          data.then(res => {
            this.$refs["scenePop"].setData(
              res.result.recordsets[0].features.features[0],
              attr
            );
            this.$refs["scenePop"].isVisible = true;
          });
        }
      }
    }
  },
  computed: {
    ...mapGetters("user", ["allLayers", "allBaseMapLayers"]),
    ...mapState({
      baseLayers(state) {
        return state.user.baseLayers;
      },
      // 地图模块控件
      mapModuleIndex(state) {
        return state.eswyzt.mapModuleIndex;
      },
      indexMap(state) {
        return state.user.sceneIndexMap;
      },
      isVisible(state) {
        return !!state.eswyzt.layerSelectorVisible;
      }
    })
  },
  beforeDestroy() {
    this.mapServiceRight.off("map.click", this.mapClickEvent);
    this.mapServiceRight.off("map.init", this.mapInitComplete); // 解绑地图加载完成事件
    this.$store.commit("eswyzt/setCurrentSearchLayer", undefined);
    this.$store.commit("eswyzt/setAttributeTable", false);
    this.$store.commit("eswyzt/setShowLayerLegend", undefined);
    this.$store.commit("eswyzt/setShowLayerStatics", undefined);
    this.$store.commit("eswyzt/setSwitchMapModuleIndex", 0);
    this.$store.commit("eswyzt/setIsShowAttribute", false);
  }
 
};
</script>

<style scoped>
.mapFunction_esw {
  top: 0;
  left: 50%;
  float: left;
  position: absolute;
}
</style>
